<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    //分类添加
    public function getAdd()
    {
    	// 解析模板 
    	$cates = self::CateList();
    	return view('Admin.cate.add',['cates' => $cates]);
    }

    // 数据添加
    public function postInsert(Request $request)
    {
    	$data = $request -> only(['name','pid']);
    	if($data['pid'] == 0){
    	$data['path'] = '0';
    	}else{
    		$res = DB::table('cate')->where('id',$data['pid']) -> first();
    		$data['path'] = $res->path.','.$data['pid'];
    	}
    	$res = DB::table('cate') -> insert($data);
    	if($res){
    		return redirect('/admin/cate/index') -> with('success','添加成功');
    	}else{
    		return back() -> with('error','添加失败');
    	}
    }
 	public function getIndex()
    {	
    	$cates = self::CateList();
    	foreach ($cates as $k => $v) {
    		if($v->pid != 0){
    			$res = DB::table('cate')->where('id',$v->pid)->first();
    			$cates[$k] -> path = $res -> name;
    		}else{
    			$cates[$k] -> path = '顶级分类';
    		}
    	}
    	return view('admin.cate.index',['cates'=>$cates]);
    }
    static public function CateList()
    {
    	$cates = DB::select('select *,concat(path,",",id) as paths from cate order by paths');

		foreach ($cates as $k => $v) {
    		$arr = explode(',',$v->path);
    		$len = count($arr)-1;
    		$cates[$k] -> name = str_repeat('|__',$len).$v -> name;
    	}
    	return $cates;
    }

    // 删除分类
    public function postDelete(Request $request)
    {
    	// 获取id
    	$id = $request -> input('id');
    	// 检测是否有子分类
    	$res = DB::table('cate')->where('pid',$id) -> count();
    	if($res > 0){
    		return 1;
    	}
    	// 执行删除
    	$res = DB::table('cate') -> where('id',$id) -> delete();
    	if($res){
    		echo 2;
    	}else{
    		echo 0;
    	}
    }
    public function getEdit($id)
    {
    	$cate = DB::table('cate') -> where('id',$id) -> first();
    	$cates = self::CateList();
    	return view('admin.cate.edit',['cate'=>$cate,'cates' => $cates]);
    }

    // 分类数据修改
    public function postUpdate(Request $request)
    {
    	$id = $request -> input('id');
    	$res = DB::table('cate')->where('pid',$id) -> count();
    	if($res > 0){
    		return back() -> with('error','不能修改');
    	}else{
    		DB::table('cate') -> where('id',$id) -> update($data);
    		$data['path'] = $res->path.','.$data['pid'];
    	}
    }
}